<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/11
 * Time: 10:36
 */

namespace HiCommon\Service;

use JPush\Client as JPush;
use HiCommon\Repository\LogRepository;

class JpushService extends BaseService
{

    protected static $client = null;

    //推送类型
    const PUSH_TYPE_ALL = 1;
    const PUSH_TYPE_TAG = 2;
    const PUSH_TYPE_ALIAS = 3;
    const PUSH_TYPE_REG_ID = 4;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    /**
     * 获取实例
     */
    public function getInstance()
    {
        if (!self::$client) {
            self::$client = new JPush(config('jpush.app_key'), config('jpush.master_secret'), null);
        }
        return self::$client;
    }

    /**
     *  给指定用户推送消息
     *  hinq 2020 5 13
     *
     **/
    public function pushNotifyToone( array $arr_input ){

        if( empty( $arr_input['user_id'] ) ){
            return hello_error('用户id不能为空');
        }
        //获取指定用户的极光数据
        $arr_option['field'] = ['id','jpush_reg_id'];
        $arr_option['with'] = ['user_jpush'];

        $arr_user = \HiCommon\Repository\UsersRepository::get_one( $arr_input['user_id'] , $arr_option);

        if( $arr_input['extras']['pid'] == 1 ){    //系统消息
              if( isset( $arr_user['user_jpush'] ) && $arr_user['user_jpush']['sys'] != 1 ){  //不接收推送消息
                  return hello_success('ok');
              }
        }elseif ( $arr_input['extras']['pid'] == 2 ){        //活动消息  活动消息不会走这里
            if( isset( $arr_user['user_jpush'] ) && $arr_user['user_jpush']['activity'] != 1 ){  //不接收推送消息
                return hello_success('ok');
            }
        }else{      //订单消息
            if( isset( $arr_user['user_jpush'] ) && $arr_user['user_jpush']['order'] != 1 ){  //不接收推送消息
                return hello_success('ok');
            }
        }

        if( empty( $arr_user->first() )){
            $arrlog = [
                'platform' => '非全平台',      //推送平台
                'title' => $arr_input['title'],      //推送平台
                'content' => $arr_input['content'],      //推送平台
                'send_time' => date('Y-m-d H:i:s'),     //发放的时间
                'msg' => '推送消息发送失败',
                'error_msg' => '用户信息获取失败',
                'status'=>2
            ];
            LogRepository::record_send_jpush( (array) $arrlog );
            return hello_error('用户信息获取失败');
        }
        if( empty( $arr_user['jpush_reg_id'] ) ){  //没有设置极光id
            $arrlog = [
                'platform' => '非全平台',      //推送平台
                'title' => $arr_input['title'],      //推送平台
                'content' => $arr_input['content'],      //推送平台
                'send_time' => date('Y-m-d H:i:s'),     //发放的时间
                'msg' => '推送消息发送失败',
                'error_msg' => '推送指定用户失败，未找到指定用户信息',
                'status'=>2
            ];
            LogRepository::record_send_jpush( (array) $arrlog );
            return hello_error('推送指定用户失败，未找到指定用户信息');
        }
        if( empty( $arr_input['content'] ) ) {
            $arrlog = [
                'platform' => '非全平台',      //推送平台
                'title' => $arr_input['title'],      //推送平台
                'content' => $arr_input['content'],      //推送平台
                'send_time' => date('Y-m-d H:i:s'),     //发放的时间
                'msg' => '推送消息发送失败',
                'error_msg' => '推送内容不能为空',
                'status'=>2
            ];
            LogRepository::record_send_jpush( (array) $arrlog );
            return hello_error('推送指定用户失败，未找到指定用户信息');
        }

        $temp = explode( '_' , $arr_user['jpush_reg_id'] );
        $params['platform'] = $temp[1];             //推送平台
        $params['title'] = $arr_input['title'];     //安卓推送的标题
        $params['content'] = $arr_input['content'];  //安卓推送的内容
        $params['type'] = 4;                //4:指定用户推送
        $params['reg_id'] = $temp[0];       //指定用户的极光id
        $params['extras'] = $arr_input['extras'];           //扩展字段
        $params['ios']['title'] = empty( $arr_input['title'] ) ? '' : $arr_input['title'];      //ios的推送标题
        $params['ios']['body'] = $arr_input['content'];     //ios的推送内容
        return self::pushNotify( (array) $params );
    }


    /**
     * 给android或ios推送消息
     */
    public function pushNotify($params)
    {
        //推送平台 ['android' , 'ios'] 或 all 或 ['android']
        $platform = $params['platform'] ?? 'all';
        //推送标题
        $title = $params['title'] ?? '';
        //推送内容
        $content = $params['content'] ?? '';
        //通知栏样式ID
        $builder_id = $params['builder_id'] ?? 0;
        //附加字段
        $extras = $params['extras'] ?? '';
        //推送类型
        $type = $params['type'] ?? '';  //默认推给所有用户
        //推送目标(注册ID)
        $reg_id = $params['reg_id'] ?? '';
        //推送目标(标签)
        $tag = $params['tag'] ?? '';
        //推送目标(别名)
        $alias = $params['alias'] ?? '';
        //ios推送标题
        $ios_list = $params['ios'] ?? '';
        try {
            $push = self::getInstance()->push();
            //设置平台
            $push->setPlatform($platform);
            switch ($type) {
                case self::PUSH_TYPE_ALL:
                    $push->addAllAudience();
                    break;
                case self::PUSH_TYPE_TAG:
                    $push->addTag($tag);
                    break;
                case self::PUSH_TYPE_ALIAS:
                    $push->addAlias($alias);
                    break;
                case self::PUSH_TYPE_REG_ID:
                    $push->addRegistrationId($reg_id);
                    break;
            }
            $push->androidNotification($content, [
                'title' => $title,
                'builder_id' => $builder_id,
                'extras' => $extras,
            ])->iosNotification($ios_list, [
                'sound' => 'sound',   //通知提示声音或警告通知
                'badge' => '+1',   //角标数字
                'extras' => $extras   //附加字段
            ])->options([
                'apns_production' => config('jpush.apns_production', true),
                //表示离线消息保留时长(秒)
                'time_to_live' => 86400,
            ]);
            $response = $push->send();
            if ($response['http_code'] != 200) {
                $arrlog = [
                    'platform' => $params['platform'],      //推送平台
                    'title' => $params['title'],      //推送平台
                    'content' => $params['content'],      //推送平台
                    'send_time' => date('Y-m-d H:i:s'),
                    'msg' => '推送消息发送失败',
                    'error_msg' => json_encode($response, JSON_UNESCAPED_UNICODE),
                    'status' => 2,
                ];
                LogRepository::record_send_jpush( (array) $arrlog );
            }else{
                $arrlog = [
                    'platform' => $params['platform'],      //推送平台
                    'title' => $params['title'],      //推送平台
                    'content' => $params['content'],      //推送平台
                    'send_time' => date('Y-m-d H:i:s'),
                    'msg' => '推送消息发送成功',
                    'status' => 1,
                    'jpush_timestamp' =>$response['headers']['x-jpush-timestamp'], // 极光推送的时间
                    'jpush_msg_id' =>$response['body']['msg_id'],
                    'jpush_sendno' =>$response['body']['sendno'],
                ];
                LogRepository::record_send_jpush( (array) $arrlog );
            }
            return hello_success('ok');
        } catch (\Throwable $e) {
            $arrlog = [
                'platform' => $params['platform'],      //推送平台
                'title' => $params['title'],      //推送平台
                'content' => $params['content'],      //推送平台
                'send_time' => date('Y-m-d H:i:s'),     //发放的时间
                'msg' => '推送消息发送失败',
                'error_msg' => $e->getMessage(),
                'status'=>2
            ];
            LogRepository::record_send_jpush( (array) $arrlog );
            return hello_error($e->getMessage());

        }
    }

}